<template>
  <div class="questionnaire-container">
    <h2>心理焦虑评测问卷</h2>
    <form @submit.prevent="submitQuestionnaire">
      <div v-for="(question, index) in questions" :key="question.id" class="form-group">
        <label>{{question.id}}、{{ question.questionText }}</label>

        <!-- 单选框：是/否 -->
        <div>
          <input
            type="radio"
            :id="'question_' + question.id + '_yes'"
            :name="'question_' + question.id"
            v-model="answers[index]"
            :value="'是'"
            required
          />
          <label :for="'question_' + question.id + '_yes'">是</label>

          <input
            type="radio"
            :id="'question_' + question.id + '_no'"
            :name="'question_' + question.id"
            v-model="answers[index]"
            :value="'否'"
            required
          />
          <label :for="'question_' + question.id + '_no'">否</label>
        </div>
      </div>
      <button type="submit" class="btn btn-primary">提交问卷</button>
    </form>
    <p v-if="errorMessage" class="text-danger">{{ errorMessage }}</p>
  </div>
</template>

<script>
export default {
  name: 'QuestionnairePage',
  data() {
    return {
      questions: [],
      answers: [],  // 存储每个问题的答案
      errorMessage: "",
    };
  },
  created() {
    this.loadQuestions();
  },
  methods: {
    // 加载问题列表
    async loadQuestions() {
      const userId = localStorage.getItem("token");  // 从localStorage中获取用户ID
      if (userId==="undefined") {
        this.errorMessage = "请先登录";
        this.$router.push("/login");
      }
      try {
        const response = await this.$axios.get("/questionnaire/questions",{
            headers: {
              "Authorization": `Bearer ${localStorage.getItem("token")}`, // 添加token
            },
          });
        this.questions = response.data;
        // 初始化每个问题的答案
        this.answers = this.questions.map(() => "");
      } catch (error) {
        console.error("加载问题失败", error);
      }
    },
    // 提交问卷
    async submitQuestionnaire() {
      const userId = localStorage.getItem("userId");  // 从localStorage中获取用户ID

      if (!userId) {
        this.errorMessage = "请先登录";
        return;
      }

      // 构造提交数据
      const userQuestionnaireData = this.questions.map((question, index) => {
        return {
          userId: userId,  // 使用localStorage中存储的userId
          questionId: question.id,
          questionText: question.questionText,  // 问题文本
          answer: this.answers[index],  // 用户选择的答案
        };
      });
  
      try {
        // 发送请求到后端
        const response = await this.$axios.post(
          "/questionnaire/submit",
          userQuestionnaireData,
          {
            headers: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${localStorage.getItem("token")}`, // 添加token
            },
          }
        );
        console.log("问卷提交成功", response);
        this.$router.push("/index");  // 提交成功后跳转到主页
      } catch (error) {
        this.errorMessage = "问卷提交失败，请重试";
      }
    },
  },
};
</script>
  
<style scoped>
/* 页面容器 */
.questionnaire-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 标题样式 */
.questionnaire-container h2 {
  font-size: 24px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

/* 表单每一组问题 */
.form-group {
  margin-bottom: 10px;
}

/* 问题文字 */
.form-group label {
  font-size: 18px;
  color: #555;
  display: block;
  margin-bottom: 10px;
  line-height: 1.5;
}

/* 单选框容器 */
.form-group div {
  display: flex;
  align-items: center;
  gap: 15px; /* 间距 */
}

/* 单选框样式 */
.form-group input[type="radio"] {
  margin: 0;  /* 取消默认的外边距 */
  vertical-align: middle;  /* 确保单选框垂直居中 */
  width: 16px;  /* 控制单选框的大小 */
  height: 16px; /* 控制单选框的大小 */
  accent-color: #3498db; /* 自定义单选框的颜色 */
}

/* 标签样式 */
.form-group label {
  font-size: 16px;  /* 控制字体大小 */
  color: #333;  /* 控制字体颜色 */
  cursor: pointer; /* 鼠标悬停时显示为手指形状 */
  line-height: 18px;  /* 确保文字和单选框垂直对齐 */
  margin-top: 10px;  /* 调整文字位置向下 */
}

/* 单选框悬停效果 */
.form-group input[type="radio"]:hover + label {
  color: #3498db;
}

/* 按钮样式 */
button {
  background-color: #3498db;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  cursor: pointer;
  width: 100%;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #2980b9;
}

button:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

</style>
